package com.kk.mybatis.controller;

import com.kk.mybatis.common.R;
import com.kk.mybatis.entity.Material;
import com.kk.mybatis.entity.request.MaterialRequest;
import com.kk.mybatis.mapper.MaterialDynamicSqlSupport;
import com.kk.mybatis.mapper.MaterialMapper;
import com.kk.mybatis.service.MaterialService;
import net.sf.cglib.core.Local;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * @description: 动态sql测试
 * @author: Kk
 * @create: 2020-12-01 10:13
 **/
@RestController
@RequestMapping("test")
public class TestController {

    @Resource
    private MaterialMapper materialMapper;
    @Autowired
    private MaterialService materialService;

    MaterialDynamicSqlSupport.Material material = MaterialDynamicSqlSupport.material;

    //模糊查询
    @PostMapping("search")
    public R search(@RequestBody MaterialRequest request){
        SelectStatementProvider statementProvider= SqlBuilder.select(material.allColumns())
                .from(material)
                .where(material.title,isLikeWhenPresent(request.getTitle()).then(s -> "%" + s + "%"),
                        or(material.description,isLikeWhenPresent(request.getDescription()).then(this::addWildcards)))
                .and(material.type,isEqualToWhenPresent(request.getType()))
                .build()
                .render(RenderingStrategies.MYBATIS3);
        List<Material> materials = materialMapper.selectMany(statementProvider);
        return R.ok().data("materials",materials);
    }

    private String addWildcards(String s) {
        return "%" + s + "%";
    }

    @GetMapping("batchInsert")
    public R batchInsert(){
        List<Material> materials = new ArrayList<>();
        for (int i=0;i<5;i++){
            Material material = new Material();
            material.setTitle("test"+i);
            material.setUrl("url");
            material.setType(i%3);
            material.setScore(0);
            material.setDescription("description"+i);
            material.setCreateTime(LocalDateTime.now());
            material.setUpdateTime(LocalDateTime.now());
            materials.add(material);
        }

        boolean flag = materialService.saveBatch(materials);
        System.out.println("请在数据库中查看"+flag);

        //用于测试test7 批量删除
        List<Integer> mIds = materials.stream().map(Material::getId).collect(Collectors.toList());
        System.out.println(mIds);
        return R.ok();
    }
}
